package aufgabe1;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class GraphFileReader {

	private static String text;

	private static ArrayList<Edge> edges = new ArrayList<Edge>();
	private static ArrayList<Vertice> nodes = new ArrayList<Vertice>();
	private static String V;
	private static String E;
	private static String[] lines;

	public GraphFileReader(String path) {

		ladeDatei(path);
	}

	public static void ladeDatei(String path) {

		File file = new File(path);

		if (!file.canRead() || !file.isFile())
			System.exit(0);

		FileReader fr = null;
		int c;
		StringBuffer buff = new StringBuffer();
		try {
			fr = new FileReader(file);
			while ((c = fr.read()) != -1) {
				buff.append((char) c);

			}
			fr.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		text = buff.toString();
		lines = text.split(System.getProperty("line.separator"));

		loadNodes();
		loadEdges();

	}

	private static void loadNodes() {
		V = lines[0];

		if (V.startsWith("V")) {
			V = V.substring(3, V.length() - 1);
			String[] temp = V.split(",");
			for (int i = 0; i < temp.length; i++) {
				nodes.add(new Vertice(Integer.parseInt(temp[i])));
			}

		}

	}

	private static void loadEdges() {
		ArrayList<String> temp = new ArrayList<String>();

		E = lines[1];

		if (E.startsWith("E")) {

			E = E.substring(3, E.length() - 1);

			for (int i = 0; i < E.length(); i++) {
				if (E.charAt(i) == '[') {
					int j = 1;
					while (E.charAt(i + j) != ']') {
						j++;
					}
					temp.add(E.substring(i + 1, i + j));
					i += j;
				}
			}
		}

		for (String node : temp) {
			String[] temp2 = node.split(",");

			Vertice start = getNodes().get(Integer.parseInt(temp2[0]) - 1);
			Vertice end = getNodes().get(Integer.parseInt(temp2[1]) - 1);
			int value = Integer.parseInt(temp2[2]);

			edges.add(new Edge(start, end, value));

		}

	}

	public static ArrayList<Vertice> getNodes() {

		return nodes;

	}

	public static ArrayList<Edge> getEdges() {

		return edges;

	}
}
